home *** CD-ROM | disk | FTP | other *** search
/ The CICA Windows Explosion! / The CICA Windows Explosion! - Disc 2.iso / programr / fileutil.zip / LS.C < prev    next >
C/C++ Source or Header  |  1992-02-22  |  47KB  |  2,051 lines

  1. /* `dir', `vdir' and `ls' directory listing programs for GNU.
  2.    Copyright (C) 1985, 1988, 1989, 1990 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* MS-DOS port (c) 1990 by Thorsten Ohl, ohl@gnu.ai.mit.edu
  19.    This port is also distributed under the terms of the
  20.    GNU General Public License as published by the
  21.    Free Software Foundation.
  22.  
  23.    Please note that this file is not identical to the
  24.    original GNU release, you should have received this
  25.    code as patch to the official release.  */
  26.  
  27. #ifdef MSDOS
  28. static char RCS_Id[] =
  29.   "$Header: e:/gnu/fileutil/RCS/ls.c 1.4.0.2 90/09/19 11:18:27 tho Exp $";
  30.  
  31. static char RCS_Revision[] = "$Revision: 1.4.0.2 $";
  32.  
  33. #define VERSION \
  34.   "GNU %s, Version %.*s (compiled %s %s for MS-DOS)\n", PROGNAME, \
  35.   (sizeof RCS_Revision - 14), (RCS_Revision + 11), __DATE__, __TIME__
  36.  
  37. #define COPYING \
  38.   "This is free software, distributed under the terms of the\n" \
  39.   "GNU General Public License.  For details, see the file COPYING.\n"
  40. #endif /* MSDOS */
  41.  
  42. /* If the macro MULTI_COL is defined,
  43.    the multi-column format is the default regardless
  44.    of the type of output device.
  45.    This is for the `dir' program.
  46.  
  47.    If the macro LONG_FORMAT is defined,
  48.    the long format is the default regardless of the
  49.    type of output device.
  50.    This is for the `vdir' program.
  51.  
  52.    If neither is defined,
  53.    the output format depends on whether the output
  54.    device is a terminal.
  55.    This is for the `ls' program. */
  56.  
  57. /* Written by Richard Stallman and David MacKenzie. */
  58.  
  59. #include <sys/types.h>
  60. #ifdef _POSIX_SOURCE
  61. #define S_IEXEC S_IXUSR
  62. #else
  63. #ifndef MSDOS
  64. #include <sys/ioctl.h>
  65. #endif /* not MSDOS */
  66. #endif
  67. #include <stdio.h>
  68. #ifndef MSDOS
  69. #include <grp.h>
  70. #endif
  71. #include <pwd.h>
  72. #include <getopt.h>
  73. #include "system.h"
  74.  
  75. /* Return an int indicating the result of comparing two longs. */
  76. #ifdef INT_16_BITS
  77. #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b) ? 1 : 0)
  78. #else
  79. #define longdiff(a, b) ((a) - (b))
  80. #endif
  81.  
  82. #ifdef STDC_HEADERS
  83. #include <errno.h>
  84. #include <stdlib.h>
  85. #include <time.h>
  86. #else
  87. char *ctime ();
  88. char *getenv ();
  89. char *malloc ();
  90. char *realloc ();
  91. long time ();
  92.  
  93. extern int errno;
  94. #endif
  95.  
  96. #ifdef MSDOS
  97. #include <string.h>
  98. #include <io.h>
  99.  
  100. #include <gnulib.h>
  101.  
  102. extern  int glob_match (char *, char *, int);
  103. extern  void mode_string (unsigned short mode, char *str);
  104. extern  void main (int, char **);
  105. extern  int argmatch (char *, char **);
  106. extern  int decode_switches (int, char **);
  107. extern  void invalid_arg (char *, char *, int);
  108. extern  void queue_directory (char *, char *);
  109. extern  void print_dir (char *, char *);
  110. extern  void add_ignore_pattern (char *);
  111. extern  int file_interesting (struct direct *);
  112. extern  void clear_files (void);
  113. extern  int gobble_file (char *, int, char *);
  114. extern  void extract_dirs_from_files (char *, int);
  115. extern  int is_not_dot_or_dotdot (char *);
  116. extern  void sort_files (void);
  117. extern  int compare_ctime (struct file *, struct file *);
  118. extern  int rev_cmp_ctime (struct file *, struct file *);
  119. extern  int compare_mtime (struct file *, struct file *);
  120. extern  int rev_cmp_mtime (struct file *, struct file *);
  121. extern  int compare_atime (struct file *, struct file *);
  122. extern  int rev_cmp_atime (struct file *, struct file *);
  123. extern  int compare_size (struct file *, struct file *);
  124. extern  int rev_cmp_size (struct file *, struct file *);
  125. extern  int compare_name (struct file *, struct file *);
  126. extern  int rev_cmp_name (struct file *, struct file *);
  127. extern  int compare_extension (struct file *file1, struct file *file2);
  128. extern  int rev_cmp_extension (struct file *file1, struct file *file2);
  129. extern  void print_current_files (void);
  130. extern  void print_long_format (struct file *);
  131. extern  void print_name_with_quoting (char *);
  132. extern  void print_file_name_and_frills (struct file *);
  133. extern  void print_type_indicator (unsigned int);
  134. extern  int length_of_file_name_and_frills (struct file *);
  135. extern  void print_many_per_line (void);
  136. extern  void print_horizontal (void);
  137. extern  void print_with_commas (void);
  138. extern  char *getuser (unsigned short);
  139. extern  char *getgroup (unsigned short);
  140. extern  void indent (int, int);
  141. extern  char *copystring (char *);
  142. extern  void attach (char *, char *, char *);
  143. extern  char *basename (char *);
  144. extern  void usage (void);
  145.  
  146. #else /* not MSDOS */
  147.  
  148. struct group *getgrgid ();
  149. struct passwd *getpwuid ();
  150. int glob_match ();
  151. void mode_string ();
  152.  
  153. char *copystring ();
  154. char *getgroup ();
  155. char *getuser ();
  156. char *make_link_path ();
  157. char *xmalloc ();
  158. char *xrealloc ();
  159. int argmatch ();
  160. int compare_atime ();
  161. int rev_cmp_atime ();
  162. int compare_ctime ();
  163. int rev_cmp_ctime ();
  164. int compare_mtime ();
  165. int rev_cmp_mtime ();
  166. int compare_size ();
  167. int rev_cmp_size ();
  168. int compare_name ();
  169. int rev_cmp_name ();
  170. int compare_extension ();
  171. int rev_cmp_extension ();
  172. int decode_switches ();
  173. int file_interesting ();
  174. int gobble_file ();
  175. int is_not_dot_or_dotdot ();
  176. int length_of_file_name_and_frills ();
  177. void add_ignore_pattern ();
  178. void attach ();
  179. void clear_files ();
  180. void error ();
  181. void extract_dirs_from_files ();
  182. void get_link_name ();
  183. void indent ();
  184. void invalid_arg ();
  185. void print_current_files ();
  186. void print_dir ();
  187. void print_file_name_and_frills ();
  188. void print_horizontal ();
  189. void print_long_format ();
  190. void print_many_per_line ();
  191. void print_name_with_quoting ();
  192. void print_type_indicator ();
  193. void print_with_commas ();
  194. void queue_directory ();
  195. void sort_files ();
  196. void usage ();
  197.  
  198. #endif /* not MSDOS */
  199.  
  200. enum filetype
  201. {
  202.   symbolic_link,
  203.   directory,
  204.   arg_directory,        /* Directory given as command line arg. */
  205.   normal            /* All others. */
  206. };
  207.  
  208. struct file
  209. {
  210.   /* The file name. */
  211.   char *name;
  212.  
  213.   struct stat stat;
  214.  
  215.   /* For symbolic link, name of the file linked to, otherwise zero. */
  216.   char *linkname;
  217.  
  218.   /* For symbolic link and long listing, st_mode of file linked to, otherwise
  219.      zero. */
  220.   unsigned int linkmode;
  221.  
  222.   enum filetype filetype;
  223. };
  224.  
  225. /* The table of files in the current directory:
  226.  
  227.    `files' points to a vector of `struct file', one per file.
  228.    `nfiles' is the number of elements space has been allocated for.
  229.    `files_index' is the number actually in use.  */
  230.  
  231. /* Address of block containing the files that are described.  */
  232.  
  233. struct file *files;
  234.  
  235. /* Length of block that `files' points to, measured in files.  */
  236.  
  237. int nfiles;
  238.  
  239. /* Index of first unused in `files'.  */
  240.  
  241. int files_index;
  242.  
  243. /* Record of one pending directory waiting to be listed.  */
  244.  
  245. struct pending
  246. {
  247.   char *name;
  248.   /* If the directory is actually the file pointed to by a symbolic link we
  249.      were told to list, `realname' will contain the name of the symbolic
  250.      link, otherwise zero. */
  251.   char *realname;
  252.   struct pending *next;
  253. };
  254.  
  255. struct pending *pending_dirs;
  256.  
  257. /* Current time (seconds since 1970).  When we are printing a file's time,
  258.    include the year if it is more than 6 months before this time.  */
  259.  
  260. long current_time;
  261.  
  262. /* The number of digits to use for block sizes.
  263.    4, or more if needed for bigger numbers.  */
  264.  
  265. int block_size_size;
  266.  
  267. /* The name the program was run with, stripped of any leading path. */
  268. char *program_name;
  269.  
  270. /* Option flags */
  271.  
  272. /* long_format for lots of info, one per line.
  273.    one_per_line for just names, one per line.
  274.    many_per_line for just names, many per line, sorted vertically.
  275.    horizontal for just names, many per line, sorted horizontally.
  276.    with_commas for just names, many per line, separated by commas.
  277.  
  278.    -l, -1, -C, -x and -m control this parameter.  */
  279.  
  280. enum format
  281. {
  282.   long_format,            /* -l */
  283.   one_per_line,            /* -1 */
  284.   many_per_line,        /* -C */
  285.   horizontal,            /* -x */
  286.   with_commas            /* -m */
  287. };
  288.  
  289. enum format format;
  290.  
  291. /* Type of time to print or sort by.  Controlled by -c and -u.  */
  292.  
  293. enum time_type
  294. {
  295.   time_mtime,            /* default */
  296.   time_ctime,            /* -c */
  297.   time_atime            /* -u */
  298. };
  299.  
  300. enum time_type time_type;
  301.  
  302. /* The file characteristic to sort by.  Controlled by -t, -S, -U, -X. */
  303.  
  304. enum sort_type
  305. {
  306.   sort_none,            /* -U */
  307.   sort_name,            /* default */
  308.   sort_extension,        /* -X */
  309.   sort_time,            /* -t */
  310.   sort_size            /* -S */
  311. };
  312.  
  313. enum sort_type sort_type;
  314.  
  315. /* Direction of sort.
  316.    0 means highest first if numeric,
  317.    lowest first if alphabetic;
  318.    these are the defaults.
  319.    1 means the opposite order in each case.  -r  */
  320.  
  321. int sort_reverse;
  322.  
  323. /* Nonzero means print the user and group id's as numbers rather
  324.    than as names.  -n  */
  325.  
  326. int numeric_users;
  327.  
  328. /* Nonzero means mention the size in 512 byte blocks of each file.  -s  */
  329.  
  330. int print_block_size;
  331.  
  332. /* Nonzero means show file sizes in kilobytes instead of blocks
  333.    (the size of which is system-dependant).  -k */
  334.  
  335. int kilobyte_blocks;
  336.  
  337. /* none means don't mention the type of files.
  338.    all means mention the types of all files.
  339.    not_programs means do so except for executables.
  340.  
  341.    Controlled by -F and -p.  */
  342.  
  343. enum indicator_style
  344. {
  345.   none,                /* default */
  346.   all,                /* -F */
  347.   not_programs            /* -p */
  348. };
  349.  
  350. enum indicator_style indicator_style;
  351.  
  352. /* Nonzero means mention the inode number of each file.  -i  */
  353.  
  354. int print_inode;
  355.  
  356. /* Nonzero means when a symbolic link is found, display info on
  357.    the file linked to.  -L  */
  358.  
  359. int trace_links;
  360.  
  361. /* Nonzero means when a directory is found, display info on its
  362.    contents.  -R  */
  363.  
  364. int trace_dirs;
  365.  
  366. /* Nonzero means when an argument is a directory name, display info
  367.    on it itself.  -d  */
  368.  
  369. int immediate_dirs;
  370.  
  371. /* Nonzero means don't omit files whose names start with `.'.  -A */
  372.  
  373. int all_files;
  374.  
  375. /* Nonzero means don't omit files `.' and `..'
  376.    This flag implies `all_files'.  -a  */
  377.  
  378. int really_all_files;
  379.  
  380. /* A linked list of shell-style globbing patterns.  If a non-argument
  381.    file name matches any of these patterns, it is omitted.
  382.    Controlled by -I.  Multiple -I options accumulate.
  383.    The -B option adds `*~' and `.*~' to this list.  */
  384.  
  385. struct ignore_pattern
  386. {
  387.   char *pattern;
  388.   struct ignore_pattern *next;
  389. };
  390.  
  391. struct ignore_pattern *ignore_patterns;
  392.  
  393. /* Nonzero means quote nongraphic chars in file names.  -b  */
  394.  
  395. int quote_funny_chars;
  396.  
  397. /* Nonzero means output nongraphic chars in file names as `?'.  -q  */
  398.  
  399. int qmark_funny_chars;
  400.  
  401. /* Nonzero means output each file name using C syntax for a string.
  402.    Always accompanied by `quote_funny_chars'.
  403.    This mode, together with -x or -C or -m,
  404.    and without such frills as -F or -s,
  405.    is guaranteed to make it possible for a program receiving
  406.    the output to tell exactly what file names are present.  -Q  */
  407.  
  408. int quote_as_string;
  409.  
  410. /* The number of chars per hardware tab stop.  -T */
  411. int tabsize;
  412.  
  413. /* Nonzero means we are listing the working directory because no
  414.    non-option arguments were given. */
  415.  
  416. int dir_defaulted;
  417.  
  418. /* Nonzero means print each directory name before listing it. */
  419.  
  420. int print_dir_name;
  421.  
  422. /* The line length to use for breaking lines in many-per-line format.
  423.    Can be set with -w.  */
  424.  
  425. int line_length;
  426.  
  427. /* If nonzero, the file listing format requires that stat be called on
  428.    each file. */
  429.  
  430. int format_needs_stat;
  431.  
  432. void
  433. main (argc, argv)
  434.      int argc;
  435.      char **argv;
  436. {
  437.   register int i;
  438.   register struct pending *thispend;
  439.  
  440.   dir_defaulted = 1;
  441.   print_dir_name = 1;
  442.   pending_dirs = 0;
  443.   current_time = time ((long *) 0);
  444.  
  445.   program_name = argv[0];
  446.   i = decode_switches (argc, argv);
  447.  
  448.   format_needs_stat = sort_type == sort_time || sort_type == sort_size
  449.     || format == long_format
  450.     || trace_links || trace_dirs || indicator_style != none
  451.     || print_block_size || print_inode;
  452.  
  453.   nfiles = 100;
  454.   files = (struct file *) xmalloc (sizeof (struct file) * nfiles);
  455.   files_index = 0;
  456.  
  457.   clear_files ();
  458.  
  459.   if (i < argc)
  460.     dir_defaulted = 0;
  461.  
  462. #ifdef MSDOS
  463.   for (; i < argc; i++)
  464.     {
  465.       if (strlen (argv[i]) == 2 && argv[i][1] == ':')
  466.     {
  467.       /* The user wants the cwd on another drive.  Help
  468.          DOS by appending a `.'!  (This allows to stat()
  469.          the directory.)  */
  470.       char *temp = (char *) xmalloc (4);
  471.       strcpy (temp, argv[i]);
  472.       strcat (temp, ".");
  473.       argv[i] = temp;
  474.     }
  475.  
  476.       gobble_file (argv[i], 1, "");
  477.     }
  478. #else /* not MSDOS */
  479.   for (; i < argc; i++)
  480.     gobble_file (argv[i], 1, "");
  481. #endif /* not MSDOS */
  482.  
  483.   if (dir_defaulted)
  484.     {
  485.       if (immediate_dirs)
  486.     gobble_file (".", 1, "");
  487.       else
  488.     queue_directory (".", 0);
  489.     }
  490.  
  491.   if (files_index)
  492.     {
  493.       sort_files ();
  494.       if (!immediate_dirs)
  495.     extract_dirs_from_files ("", 0);
  496.       /* `files_index' might be zero now.  */
  497.     }
  498.   if (files_index)
  499.     {
  500.       print_current_files ();
  501.       if (pending_dirs)
  502.     putchar ('\n');
  503.     }
  504.   else if (pending_dirs && pending_dirs->next == 0)
  505.     print_dir_name = 0;
  506.  
  507.   while (pending_dirs)
  508.     {
  509.       thispend = pending_dirs;
  510.       pending_dirs = pending_dirs->next;
  511.       print_dir (thispend->name, thispend->realname);
  512.       free (thispend->name);
  513.       if (thispend->realname)
  514.     free (thispend->realname);
  515.       free (thispend);
  516.       print_dir_name = 1;
  517.     }
  518.  
  519.   exit (0);
  520. }
  521.  
  522. struct option long_options[] =
  523. {
  524. #ifdef MSDOS
  525.   {"copying", 0, NULL, 30},
  526.   {"version", 0, NULL, 31},
  527. #endif
  528.   {"all", 0, 0, 'a'},
  529.   {"escape", 0, 0, 'b'},
  530.   {"directory", 0, 0, 'd'},
  531.   {"inode", 0, 0, 'i'},
  532.   {"kilobytes", 0, 0, 'k'},
  533.   {"numeric-uid-gid", 0, 0, 'n'},
  534.   {"hide-control-chars", 0, 0, 'q'},
  535.   {"reverse", 0, 0, 'r'},
  536.   {"size", 0, 0, 's'},
  537.   {"width", 1, 0, 'w'},
  538.   {"almost-all", 0, 0, 'A'},
  539.   {"ignore-backups", 0, 0, 'B'},
  540.   {"classify", 0, 0, 'F'},
  541.   {"file-type", 0, 0, 'F'},
  542.   {"ignore", 1, 0, 'I'},
  543.   {"dereference", 0, 0, 'L'},
  544.   {"literal", 0, 0, 'N'},
  545.   {"quote-name", 0, 0, 'Q'},
  546.   {"recursive", 0, 0, 'R'},
  547.   {"format", 1, 0, 12},
  548.   {"sort", 1, 0, 10},
  549.   {"tabsize", 1, 0, 'T'},
  550.   {"time", 1, 0, 11},
  551.   {0, 0, 0, 0}
  552. };
  553.  
  554. char *format_args[] =
  555. {
  556.   "verbose", "long", "commas", "horizontal", "across",
  557.   "vertical", "single-column", 0
  558. };
  559.  
  560. enum format formats[] =
  561. {
  562.   long_format, long_format, with_commas, horizontal, horizontal,
  563.   many_per_line, one_per_line
  564. };
  565.  
  566. char *sort_args[] =
  567. {
  568.   "none", "time", "size", "extension", 0
  569. };
  570.  
  571. enum sort_type sort_types[] =
  572. {
  573.   sort_none, sort_time, sort_size, sort_extension
  574. };
  575.  
  576. char *time_args[] =
  577. {
  578.   "atime", "access", "use", "ctime", "status", 0
  579. };
  580.  
  581. enum time_type time_types[] =
  582. {
  583.   time_atime, time_atime, time_atime, time_ctime, time_ctime
  584. };
  585.  
  586. /* Set all the option flags according to the switches specified.
  587.    Return the index of the first non-option argument.  */
  588.  
  589. int
  590. decode_switches (argc, argv)
  591.      int argc;
  592.      char **argv;
  593. {
  594.   register char *p;
  595.   int c;
  596.   int longind;
  597.  
  598.   qmark_funny_chars = 0;
  599.   quote_funny_chars = 0;
  600.  
  601.   /* initialize all switches to default settings */
  602.  
  603. #ifdef MULTI_COL
  604. #define PROGNAME "dir"
  605.   /* This is for the `dir' program.  */
  606.   format = many_per_line;
  607.   quote_funny_chars = 1;
  608. #else
  609. #ifdef LONG_FORMAT
  610. #define PROGNAME "vdir"
  611.   /* This is for the `vdir' program.  */
  612.   format = long_format;
  613.   quote_funny_chars = 1;
  614. #else
  615. #define PROGNAME "ls"
  616.   /* This is for the `ls' program.  */
  617.   if (isatty (1))
  618.     {
  619.       format = many_per_line;
  620.       qmark_funny_chars = 1;
  621.     }
  622.   else
  623.     {
  624.       format = one_per_line;
  625.       qmark_funny_chars = 0;
  626.     }
  627. #endif
  628. #endif
  629.  
  630.   time_type = time_mtime;
  631.   sort_type = sort_name;
  632.   sort_reverse = 0;
  633.   numeric_users = 0;
  634.   print_block_size = 0;
  635.   kilobyte_blocks = 0;
  636.   indicator_style = none;
  637.   print_inode = 0;
  638.   trace_links = 0;
  639.   trace_dirs = 0;
  640.   immediate_dirs = 0;
  641.   all_files = 0;
  642.   really_all_files = 0;
  643.   ignore_patterns = 0;
  644.   quote_as_string = 0;
  645.  
  646.   p = getenv ("COLUMNS");
  647.   line_length = p ? atoi (p) : 80;
  648.  
  649. #ifdef TIOCGWINSZ
  650.   {
  651.     struct winsize ws;
  652.  
  653.     if (ioctl (1, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0)
  654.       line_length = ws.ws_col;
  655.   }
  656. #endif
  657.  
  658.   p = getenv ("TABSIZE");
  659.   tabsize = p ? atoi (p) : 8;
  660.  
  661.   while ((c = getopt_long (argc, argv, "abcdgiklmnpqrstuw:xABCFI:LNQRST:UX1",
  662.                long_options, &longind)) != EOF)
  663.     {
  664.       switch (c)
  665.     {
  666.     case 'a':
  667.       all_files = 1;
  668.       really_all_files = 1;
  669.       break;
  670.       
  671.     case 'b':
  672.       quote_funny_chars = 1;
  673.       qmark_funny_chars = 0;
  674.       break;
  675.       
  676.     case 'c':
  677.       time_type = time_ctime;
  678.       break;
  679.       
  680.     case 'd':
  681.       immediate_dirs = 1;
  682.       break;
  683.       
  684.     case 'g':
  685.       /* No effect.  For BSD compatibility. */
  686.       break;
  687.  
  688.     case 'i':
  689.       print_inode = 1;
  690.       break;
  691.       
  692.     case 'k':
  693.       kilobyte_blocks = 1;
  694.       break;
  695.       
  696.     case 'l':
  697.       format = long_format;
  698.       break;
  699.       
  700.     case 'm':
  701.       format = with_commas;
  702.       break;
  703.       
  704.     case 'n':
  705.       numeric_users = 1;
  706.       break;
  707.       
  708.     case 'p':
  709.       indicator_style = not_programs;
  710.       break;
  711.       
  712.     case 'q':
  713.       qmark_funny_chars = 1;
  714.       quote_funny_chars = 0;
  715.       break;
  716.       
  717.     case 'r':
  718.       sort_reverse = 1;
  719.       break;
  720.       
  721.     case 's':
  722.       print_block_size = 1;
  723.       break;
  724.       
  725.     case 't':
  726.       sort_type = sort_time;
  727.       break;
  728.       
  729.     case 'u':
  730.       time_type = time_atime;
  731.       break;
  732.       
  733.     case 'w':
  734.       line_length = atoi (optarg);
  735.       if (line_length < 1)
  736.         error (1, 0, "invalid line width: %s", optarg);
  737.       break;
  738.       
  739.     case 'x':
  740.       format = horizontal;
  741.       break;
  742.       
  743.     case 'A':
  744.       all_files = 1;
  745.       break;
  746.       
  747.     case 'B':
  748.       add_ignore_pattern ("*~");
  749.       add_ignore_pattern (".*~");
  750.       break;
  751.       
  752.     case 'C':
  753.       format = many_per_line;
  754.       break;
  755.       
  756.     case 'F':
  757.       indicator_style = all;
  758.       break;
  759.       
  760.     case 'I':
  761.       add_ignore_pattern (optarg);
  762.       break;
  763.       
  764.     case 'L':
  765.       trace_links = 1;
  766.       break;
  767.       
  768.     case 'N':
  769.       quote_funny_chars = 0;
  770.       qmark_funny_chars = 0;
  771.       break;
  772.       
  773.     case 'Q':
  774.       quote_as_string = 1;
  775.       quote_funny_chars = 1;
  776.       qmark_funny_chars = 0;
  777.       break;
  778.       
  779.     case 'R':
  780.       trace_dirs = 1;
  781.       break;
  782.       
  783.     case 'S':
  784.       sort_type = sort_size;
  785.       break;
  786.       
  787.     case 'T':
  788.       tabsize = atoi (optarg);
  789.       if (tabsize < 1)
  790.         error (1, 0, "invalid tab size: %s", optarg);
  791.       break;
  792.  
  793.     case 'U':
  794.       sort_type = sort_none;
  795.       break;
  796.  
  797.     case 'X':
  798.       sort_type = sort_extension;
  799.       break;
  800.  
  801.     case '1':
  802.       format = one_per_line;
  803.       break;
  804.       
  805.     case 10:        /* +sort */
  806.       longind = argmatch (optarg, sort_args);
  807.       if (longind < 0)
  808.         {
  809.           invalid_arg ("sort type", optarg, longind);
  810.           usage ();
  811.         }
  812.       sort_type = sort_types[longind];
  813.       break;
  814.  
  815.     case 11:        /* +time */
  816.       longind = argmatch (optarg, time_args);
  817.       if (longind < 0)
  818.         {
  819.           invalid_arg ("time type", optarg, longind);
  820.           usage ();
  821.         }
  822.       time_type = time_types[longind];
  823.       break;
  824.  
  825.     case 12:        /* +format */
  826.       longind = argmatch (optarg, format_args);
  827.       if (longind < 0)
  828.         {
  829.           invalid_arg ("format type", optarg, longind);
  830.           usage ();
  831.         }
  832.       format = formats[longind];
  833.       break;
  834.  
  835. #ifdef MSDOS
  836.     case 30:
  837.       fprintf (stderr, COPYING);
  838.       exit (0);
  839.       break;
  840.  
  841.     case 31:
  842.       fprintf (stderr, VERSION);
  843.       exit (0);
  844.       break;
  845. #endif
  846.  
  847.     default:
  848.       usage ();
  849.     }
  850.     }
  851.  
  852.   return optind;
  853. }
  854.  
  855. /* Request that the directory named `name' have its contents listed later.
  856.    If `realname' is nonzero, it will be used instead of `name' when the
  857.    directory name is printed.  This allows symbolic links to directories
  858.    to be treated as regular directories but still be listed under their
  859.    real names. */
  860.  
  861. void
  862. queue_directory (name, realname)
  863.      char *name;
  864.      char *realname;
  865. {
  866.   struct pending *new;
  867.  
  868.   new = (struct pending *) xmalloc (sizeof (struct pending));
  869.   new->next = pending_dirs;
  870.   pending_dirs = new;
  871.   new->name = copystring (name);
  872.   if (realname)
  873.     new->realname = copystring (realname);
  874.   else
  875.     new->realname = 0;
  876. }
  877.  
  878. /* Read directory `name', and list the files in it.
  879.    If `realname' is nonzero, print its name instead of `name';
  880.    this is used for symbolic links to directories. */
  881.  
  882. void
  883. print_dir (name, realname)
  884.      char *name;
  885.      char *realname;
  886. {
  887.   register DIR *reading;
  888.   register struct direct *next;
  889.   register int total_blocks = 0;
  890.  
  891.   errno = 0;
  892.   reading = opendir (name);
  893.   if (!reading)
  894.     {
  895.       error (0, errno, "%s", name);
  896.       return;
  897.     }
  898.  
  899.   /* Read the directory entries, and insert the subfiles into the `files'
  900.      table.  */
  901.  
  902.   clear_files ();
  903.  
  904.   while (next = readdir (reading))
  905.     if (file_interesting (next))
  906.       total_blocks += gobble_file (next->d_name, 0, name);
  907.  
  908.   closedir (reading);
  909.  
  910.   /* Sort the directory contents.  */
  911.   sort_files ();
  912.  
  913.   /* If any member files are subdirectories, perhaps they should have their
  914.      contents listed rather than being mentioned here as files.  */
  915.  
  916.   if (trace_dirs)
  917.     extract_dirs_from_files (name, 1);
  918.  
  919.   if (print_dir_name)
  920.     {
  921.       if (realname)
  922.     printf ("%s:\n", realname);
  923.       else
  924.     printf ("%s:\n", name);
  925.     }
  926.  
  927.   if (format == long_format || print_block_size)
  928.     printf ("total %u\n", total_blocks);
  929.  
  930.   if (files_index)
  931.     print_current_files ();
  932.  
  933.   if (pending_dirs)
  934.     putchar ('\n');
  935. }
  936.  
  937. /* Add `pattern' to the list of patterns for which files that match are
  938.    not listed.  */
  939.  
  940. void
  941. add_ignore_pattern (pattern)
  942.      char *pattern;
  943. {
  944.   register struct ignore_pattern *ignore;
  945.  
  946.   ignore = (struct ignore_pattern *) xmalloc (sizeof (struct ignore_pattern));
  947.   ignore->pattern = pattern;
  948.   /* Add it to the head of the linked list. */
  949.   ignore->next = ignore_patterns;
  950.   ignore_patterns = ignore;
  951. }
  952.  
  953. /* Return nonzero if the file in `next' should be listed. */
  954.  
  955. int
  956. file_interesting (next)
  957.      register struct direct *next;
  958. {
  959.   register struct ignore_pattern *ignore;
  960.  
  961.   for (ignore = ignore_patterns; ignore; ignore = ignore->next)
  962.     if (glob_match (ignore->pattern, next->d_name, 1))
  963.       return 0;
  964.  
  965.   if (really_all_files
  966.       || next->d_name[0] != '.'
  967.       || (all_files
  968.       && next->d_name[1] != '\0'
  969.       && (next->d_name[1] != '.' || next->d_name[2] != '\0')))
  970.     return 1;
  971.  
  972.   return 0;
  973. }
  974.  
  975. /* Enter and remove entries in the table `files'.  */
  976.  
  977. /* Empty the table of files. */
  978.  
  979. void
  980. clear_files ()
  981. {
  982.   register int i;
  983.  
  984.   for (i = 0; i < files_index; i++)
  985.     {
  986.       free (files[i].name);
  987.       if (files[i].linkname)
  988.     free (files[i].linkname);
  989.     }
  990.  
  991.   files_index = 0;
  992.   block_size_size = 4;
  993. }
  994.  
  995. /* Add a file to the current table of files.
  996.    Verify that the file exists, and print an error message if it does not.
  997.    Return the number of blocks that the file occupies.  */
  998.  
  999. int
  1000. gobble_file (name, explicit_arg, dirname)
  1001.      char *name;
  1002.      int explicit_arg;
  1003.      char *dirname;
  1004. {
  1005.   register int blocks;
  1006.   register int val;
  1007.   register char *path;
  1008.  
  1009.   if (files_index == nfiles)
  1010.     {
  1011.       nfiles *= 2;
  1012.       files = (struct file *) xrealloc (files, sizeof (struct file) * nfiles);
  1013.     }
  1014.  
  1015.   files[files_index].linkname = 0;
  1016.   files[files_index].linkmode = 0;
  1017.  
  1018.   if (explicit_arg || format_needs_stat)
  1019.     {
  1020.       /* `path' is the absolute pathname of this file. */
  1021.  
  1022.       if (name[0] == '/' || dirname[0] == 0)
  1023.     path = name;
  1024.       else
  1025.     {
  1026.       path = (char *) alloca (strlen (name) + strlen (dirname) + 2);
  1027.       attach (path, dirname, name);
  1028.     }
  1029.  
  1030.       if (trace_links)
  1031.     {
  1032.       val = stat (path, &files[files_index].stat);
  1033.       if (val < 0)
  1034.         /* Perhaps a symbolically-linked to file doesn't exist; stat
  1035.            the link instead. */
  1036.         val = lstat (path, &files[files_index].stat);
  1037.     }
  1038.       else
  1039.     val = lstat (path, &files[files_index].stat);
  1040.       if (val < 0)
  1041.     {
  1042.       error (0, errno, "%s", path);
  1043.       return 0;
  1044.     }
  1045.  
  1046. #ifdef S_IFLNK
  1047.       if ((files[files_index].stat.st_mode & S_IFMT) == S_IFLNK)
  1048.     {
  1049.       char *linkpath;
  1050.       struct stat linkstats;
  1051.  
  1052.       get_link_name (path, &files[files_index]);
  1053.       linkpath = make_link_path (path, files[files_index].linkname);
  1054.  
  1055.       /* Stat the file linked to; automatically trace it in non-long
  1056.          listings, get its mode for the filetype indicator in long
  1057.          listings. */
  1058.       if (linkpath && lstat (linkpath, &linkstats) == 0)
  1059.         {
  1060.           if ((linkstats.st_mode & S_IFMT) == S_IFDIR
  1061.           && explicit_arg && format != long_format)
  1062.         {
  1063.           char *tempname;
  1064.  
  1065.           /* Symbolic links to directories that are mentioned on the
  1066.              command line are automatically traced if not being
  1067.              listed as files. */
  1068.           if (!immediate_dirs)
  1069.             {
  1070.               tempname = name;
  1071.               name = linkpath;
  1072.               linkpath = files[files_index].linkname;
  1073.               files[files_index].linkname = tempname;
  1074.             }
  1075.           files[files_index].stat = linkstats;
  1076.         }
  1077.           else
  1078.         files[files_index].linkmode = linkstats.st_mode;
  1079.         }
  1080.       if (linkpath)
  1081.         free (linkpath);
  1082.     }
  1083. #endif
  1084.  
  1085.       switch (files[files_index].stat.st_mode & S_IFMT)
  1086.     {
  1087. #ifdef S_IFLNK
  1088.     case S_IFLNK:
  1089.       files[files_index].filetype = symbolic_link;
  1090.       break;
  1091. #endif
  1092.  
  1093.     case S_IFDIR:
  1094.       if (explicit_arg && !immediate_dirs)
  1095.         files[files_index].filetype = arg_directory;
  1096.       else
  1097.         files[files_index].filetype = directory;
  1098.       break;
  1099.  
  1100.     default:
  1101.       files[files_index].filetype = normal;
  1102.       break;
  1103.     }
  1104.  
  1105.       blocks = convert_blocks (ST_NBLOCKS (files[files_index].stat),
  1106.                    kilobyte_blocks);
  1107.       if (blocks >= 10000 && block_size_size < 5)
  1108.     block_size_size = 5;
  1109. #ifndef MSDOS
  1110.       if (blocks >= 100000 && block_size_size < 6)
  1111.     block_size_size = 6;
  1112.       if (blocks >= 1000000 && block_size_size < 7)
  1113.     block_size_size = 7;
  1114. #endif /* not MSDOS */
  1115.     }
  1116.   else
  1117.     blocks = 0;
  1118.  
  1119.   files[files_index].name = copystring (name);
  1120.   files_index++;
  1121.  
  1122.   return blocks;
  1123. }
  1124.  
  1125. #ifdef S_IFLNK
  1126.  
  1127. /* Put the name of the file that `filename' is a symbolic link to
  1128.    into the `linkname' field of `f'. */
  1129.  
  1130. void
  1131. get_link_name (filename, f)
  1132.      char *filename;
  1133.      struct file *f;
  1134. {
  1135.   register char *linkbuf;
  1136.   register int bufsiz = f->stat.st_size;
  1137.  
  1138.   linkbuf = (char *) xmalloc (bufsiz + 1);
  1139.   linkbuf[bufsiz] = 0;
  1140.   if (readlink (filename, linkbuf, bufsiz) < 0)
  1141.     {
  1142.       error (0, errno, "%s", filename);
  1143.       free (linkbuf);
  1144.     }
  1145.   else
  1146.     f->linkname = linkbuf;
  1147. }
  1148.  
  1149. /* If `linkname' is a relative path and `path' contains one or more
  1150.    leading directories, return `linkname' with those directories
  1151.    prepended; otherwise, return a copy of `linkname'.
  1152.    If `linkname' is zero, return zero. */
  1153.  
  1154. char *
  1155. make_link_path (path, linkname)
  1156.      char *path;
  1157.      char *linkname;
  1158. {
  1159.   char *linkbuf;
  1160.   int bufsiz;
  1161.  
  1162.   if (linkname == 0)
  1163.     return 0;
  1164.  
  1165.   if (*linkname == '/')
  1166.     return copystring (linkname);
  1167.  
  1168.   /* The link is to a relative path.  Prepend any leading path
  1169.      in `path' to the link name. */
  1170.   linkbuf = rindex (path, '/');
  1171.   if (linkbuf == 0)
  1172.     return copystring (linkname);
  1173.  
  1174.   bufsiz = linkbuf - path + 1;
  1175.   linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
  1176.   strncpy (linkbuf, path, bufsiz);
  1177.   strcpy (linkbuf + bufsiz, linkname);
  1178.   return linkbuf;
  1179. }
  1180. #endif
  1181.  
  1182. /* Remove any entries from `files' that are for directories,
  1183.    and queue them to be listed as directories instead.
  1184.    `dirname' is the prefix to prepend to each dirname
  1185.    to make it correct relative to ls's working dir.
  1186.    `recursive' is nonzero if we should not treat `.' and `..' as dirs.
  1187.    This is desirable when processing directories recursively.  */
  1188.  
  1189. void
  1190. extract_dirs_from_files (dirname, recursive)
  1191.      char *dirname;
  1192.      int recursive;
  1193. {
  1194.   register int i, j;
  1195.   register char *path;
  1196.   int dirlen;
  1197.  
  1198.   dirlen = strlen (dirname) + 2;
  1199.   /* Queue the directories last one first, because queueing reverses the
  1200.      order.  */
  1201.   for (i = files_index - 1; i >= 0; i--)
  1202.     if ((files[i].filetype == directory || files[i].filetype == arg_directory)
  1203.     && (!recursive || is_not_dot_or_dotdot (files[i].name)))
  1204.       {
  1205.     if (files[i].name[0] == '/' || dirname[0] == 0)
  1206.       {
  1207.         queue_directory (files[i].name, files[i].linkname);
  1208.       }
  1209.     else
  1210.       {
  1211.         path = (char *) xmalloc (strlen (files[i].name) + dirlen);
  1212.         attach (path, dirname, files[i].name);
  1213.         queue_directory (path, files[i].linkname);
  1214.         free (path);
  1215.       }
  1216.     if (files[i].filetype == arg_directory)
  1217.       free (files[i].name);
  1218.       }
  1219.  
  1220.   /* Now delete the directories from the table, compacting all the remaining
  1221.      entries.  */
  1222.  
  1223.   for (i = 0, j = 0; i < files_index; i++)
  1224.     if (files[i].filetype != arg_directory)
  1225.       files[j++] = files[i];
  1226.   files_index = j;
  1227. }
  1228.  
  1229. /* Return non-zero if `name' doesn't end in `.' or `..'
  1230.    This is so we don't try to recurse on `././././. ...' */
  1231.  
  1232. int
  1233. is_not_dot_or_dotdot (name)
  1234.      char *name;
  1235. {
  1236.   char *t;
  1237.  
  1238.   t = rindex (name, '/');
  1239.   if (t)
  1240.     name = t + 1;
  1241.  
  1242.   if (name[0] == '.'
  1243.       && (name[1] == '\0'
  1244.       || (name[1] == '.' && name[2] == '\0')))
  1245.     return 0;
  1246.  
  1247.   return 1;
  1248. }
  1249.  
  1250. /* Sort the files now in the table.  */
  1251.  
  1252. void
  1253. sort_files ()
  1254. {
  1255.   int (*func) ();
  1256.  
  1257.   switch (sort_type)
  1258.     {
  1259.     case sort_none:
  1260.       return;
  1261.     case sort_time:
  1262.       switch (time_type)
  1263.     {
  1264.     case time_ctime:
  1265.       func = sort_reverse ? rev_cmp_ctime : compare_ctime;
  1266.       break;
  1267.     case time_mtime:
  1268.       func = sort_reverse ? rev_cmp_mtime : compare_mtime;
  1269.       break;
  1270.     case time_atime:
  1271.       func = sort_reverse ? rev_cmp_atime : compare_atime;
  1272.       break;
  1273.     }
  1274.       break;
  1275.     case sort_name:
  1276.       func = sort_reverse ? rev_cmp_name : compare_name;
  1277.       break;
  1278.     case sort_extension:
  1279.       func = sort_reverse ? rev_cmp_extension : compare_extension;
  1280.       break;
  1281.     case sort_size:
  1282.       func = sort_reverse ? rev_cmp_size : compare_size;
  1283.       break;
  1284.     }
  1285.  
  1286.   qsort (files, files_index, sizeof (struct file), func);
  1287. }
  1288.  
  1289. /* Comparison routines for sorting the files. */
  1290.  
  1291. int
  1292. compare_ctime (file1, file2)
  1293.      struct file *file1, *file2;
  1294. {
  1295.   return longdiff (file2->stat.st_ctime, file1->stat.st_ctime);
  1296. }
  1297.  
  1298. int
  1299. rev_cmp_ctime (file2, file1)
  1300.      struct file *file1, *file2;
  1301. {
  1302.   return longdiff (file2->stat.st_ctime, file1->stat.st_ctime);
  1303. }
  1304.  
  1305. int
  1306. compare_mtime (file1, file2)
  1307.      struct file *file1, *file2;
  1308. {
  1309.   return longdiff (file2->stat.st_mtime, file1->stat.st_mtime);
  1310. }
  1311.  
  1312. int
  1313. rev_cmp_mtime (file2, file1)
  1314.      struct file *file1, *file2;
  1315. {
  1316.   return longdiff (file2->stat.st_mtime, file1->stat.st_mtime);
  1317. }
  1318.  
  1319. int
  1320. compare_atime (file1, file2)
  1321.      struct file *file1, *file2;
  1322. {
  1323.   return longdiff (file2->stat.st_atime, file1->stat.st_atime);
  1324. }
  1325.  
  1326. int
  1327. rev_cmp_atime (file2, file1)
  1328.      struct file *file1, *file2;
  1329. {
  1330.   return longdiff (file2->stat.st_atime, file1->stat.st_atime);
  1331. }
  1332.  
  1333. int
  1334. compare_size (file1, file2)
  1335.      struct file *file1, *file2;
  1336. {
  1337.   return longdiff (file2->stat.st_size, file1->stat.st_size);
  1338. }
  1339.  
  1340. int
  1341. rev_cmp_size (file2, file1)
  1342.      struct file *file1, *file2;
  1343. {
  1344.   return longdiff (file2->stat.st_size, file1->stat.st_size);
  1345. }
  1346.  
  1347. int
  1348. compare_name (file1, file2)
  1349.      struct file *file1, *file2;
  1350. {
  1351.   return strcmp (file1->name, file2->name);
  1352. }
  1353.  
  1354. int
  1355. rev_cmp_name (file2, file1)
  1356.      struct file *file1, *file2;
  1357. {
  1358.   return strcmp (file1->name, file2->name);
  1359. }
  1360.  
  1361. /* Compare file extensions.  Files with no extension are `smallest'.
  1362.    If extensions are the same, compare by filenames instead. */
  1363.  
  1364. int
  1365. compare_extension (file1, file2)
  1366.      struct file *file1, *file2;
  1367. {
  1368.   register char *base1, *base2;
  1369.   register int cmp;
  1370.  
  1371.   base1 = rindex (file1->name, '.');
  1372.   base2 = rindex (file2->name, '.');
  1373.   if (base1 == 0 && base2 == 0)
  1374.     return strcmp (file1->name, file2->name);
  1375.   if (base1 == 0)
  1376.     return -1;
  1377.   if (base2 == 0)
  1378.     return 1;
  1379.   cmp = strcmp (base1, base2);
  1380.   if (cmp == 0)
  1381.     return strcmp (file1->name, file2->name);
  1382.   return cmp;
  1383. }
  1384.  
  1385. int
  1386. rev_cmp_extension (file2, file1)
  1387.      struct file *file1, *file2;
  1388. {
  1389.   register char *base1, *base2;
  1390.   register int cmp;
  1391.  
  1392.   base1 = rindex (file1->name, '.');
  1393.   base2 = rindex (file2->name, '.');
  1394.   if (base1 == 0 && base2 == 0)
  1395.     return strcmp (file1->name, file2->name);
  1396.   if (base1 == 0)
  1397.     return -1;
  1398.   if (base2 == 0)
  1399.     return 1;
  1400.   cmp = strcmp (base1, base2);
  1401.   if (cmp == 0)
  1402.     return strcmp (file1->name, file2->name);
  1403.   return cmp;
  1404. }
  1405.  
  1406. /* List all the files now in the table.  */
  1407.  
  1408. void
  1409. print_current_files ()
  1410. {
  1411.   register int i;
  1412.  
  1413.   switch (format)
  1414.     {
  1415.     case one_per_line:
  1416.       for (i = 0; i < files_index; i++)
  1417.     {
  1418.       print_file_name_and_frills (files + i);
  1419.       putchar ('\n');
  1420.     }
  1421.       break;
  1422.  
  1423.     case many_per_line:
  1424.       print_many_per_line ();
  1425.       break;
  1426.  
  1427.     case horizontal:
  1428.       print_horizontal ();
  1429.       break;
  1430.  
  1431.     case with_commas:
  1432.       print_with_commas ();
  1433.       break;
  1434.  
  1435.     case long_format:
  1436.       for (i = 0; i < files_index; i++)
  1437.     {
  1438.       print_long_format (files + i);
  1439.       putchar ('\n');
  1440.     }
  1441.       break;
  1442.     }
  1443. }
  1444.  
  1445. void
  1446. print_long_format (f)
  1447.      struct file *f;
  1448. {
  1449.   char modebuf[20];
  1450.   char timebuf[40];
  1451.   long when;
  1452.  
  1453.   mode_string (f->stat.st_mode, modebuf);
  1454.   modebuf[10] = 0;
  1455.  
  1456.   switch (time_type)
  1457.     {
  1458.     case time_ctime:
  1459.       when = f->stat.st_ctime;
  1460.       break;
  1461.     case time_mtime:
  1462.       when = f->stat.st_mtime;
  1463.       break;
  1464.     case time_atime:
  1465.       when = f->stat.st_atime;
  1466.       break;
  1467.     }
  1468.  
  1469.   strcpy (timebuf, ctime (&when));
  1470.   if (current_time - when > 6L * 30L * 24L * 60L * 60L
  1471.       || current_time - when < 0L)
  1472.     {
  1473.       /* The file is fairly old or in the future.
  1474.      POSIX says the cutoff is 6 months old;
  1475.      approximate this by 6*30 days.
  1476.      Show the year instead of the time of day.  */
  1477.       strcpy (timebuf + 11, timebuf + 19);
  1478.     }
  1479.   timebuf[16] = 0;
  1480.  
  1481.   if (print_inode)
  1482.     printf ("%6u ", f->stat.st_ino);
  1483.  
  1484.   if (print_block_size)
  1485.     printf ("%*u ", block_size_size, convert_blocks (ST_NBLOCKS (f->stat),
  1486.                              kilobyte_blocks));
  1487.  
  1488.   /* The space between the mode and the number of links is the POSIX
  1489.      "optional alternate access method flag". */
  1490.   printf ("%s %3u ", modebuf, f->stat.st_nlink);
  1491.  
  1492.   if (numeric_users)
  1493.     printf ("%-8u ", (unsigned int) f->stat.st_uid);
  1494.   else
  1495.     printf ("%-8.8s ", getuser (f->stat.st_uid));
  1496.  
  1497.   if (numeric_users)
  1498.     printf ("%-8u ", (unsigned int) f->stat.st_gid);
  1499.   else
  1500.     printf ("%-8.8s ", getgroup (f->stat.st_gid));
  1501.  
  1502. #ifdef S_IFBLK
  1503.   if ((f->stat.st_mode & S_IFMT) == S_IFCHR
  1504.       || (f->stat.st_mode & S_IFMT) == S_IFBLK)
  1505. #else /* not S_IFBLK */
  1506.   if ((f->stat.st_mode & S_IFMT) == S_IFCHR)
  1507. #endif /* not S_IFBLK */
  1508.     printf ("%3u, %3u ", major (f->stat.st_rdev), minor (f->stat.st_rdev));
  1509.   else
  1510.     printf ("%8lu ", f->stat.st_size);
  1511.  
  1512.   printf ("%s ", timebuf + 4);
  1513.  
  1514.   print_name_with_quoting (f->name);
  1515.  
  1516.   if (f->filetype == symbolic_link)
  1517.     {
  1518.       if (f->linkname)
  1519.     {
  1520.       fputs (" -> ", stdout);
  1521.       print_name_with_quoting (f->linkname);
  1522.       if (indicator_style != none)
  1523.         print_type_indicator (f->linkmode);
  1524.     }
  1525.     }
  1526.   else if (indicator_style != none)
  1527.     print_type_indicator (f->stat.st_mode);
  1528. }
  1529.  
  1530. void
  1531. print_name_with_quoting (p)
  1532.      register char *p;
  1533. {
  1534.   register unsigned char c;
  1535.  
  1536.   if (quote_as_string)
  1537.     putchar ('"');
  1538.  
  1539.   while (c = *p++)
  1540.     {
  1541.       if (quote_funny_chars)
  1542.     {
  1543.       switch (c)
  1544.         {
  1545.         case '\\':
  1546.           printf ("\\\\");
  1547.           break;
  1548.  
  1549.         case '\n':
  1550.           printf ("\\n");
  1551.           break;
  1552.  
  1553.         case '\b':
  1554.           printf ("\\b");
  1555.           break;
  1556.  
  1557.         case '\r':
  1558.           printf ("\\r");
  1559.           break;
  1560.  
  1561.         case '\t':
  1562.           printf ("\\t");
  1563.           break;
  1564.  
  1565.         case '\f':
  1566.           printf ("\\f");
  1567.           break;
  1568.  
  1569.         case ' ':
  1570.           printf ("\\ ");
  1571.           break;
  1572.  
  1573.         case '"':
  1574.           printf ("\\\"");
  1575.           break;
  1576.  
  1577.         default:
  1578.           if (c > 040 && c < 0177)
  1579.         putchar (c);
  1580.           else
  1581.         printf ("\\%03o", (unsigned int) c);
  1582.         }
  1583.     }
  1584.       else
  1585.     {
  1586.       if (c >= 040 && c < 0177)
  1587.         putchar (c);
  1588.       else if (!qmark_funny_chars)
  1589.         putchar (c);
  1590.       else
  1591.         putchar ('?');
  1592.     }
  1593.     }
  1594.  
  1595.   if (quote_as_string)
  1596.     putchar ('"');
  1597. }
  1598.  
  1599. /* Print the file name of `f' with appropriate quoting.
  1600.    Also print file size, inode number, and filetype indicator character,
  1601.    as requested by switches.  */
  1602.  
  1603. void
  1604. print_file_name_and_frills (f)
  1605.      struct file *f;
  1606. {
  1607.   if (print_inode)
  1608.     printf ("%6u ", f->stat.st_ino);
  1609.  
  1610.   if (print_block_size)
  1611.     printf ("%*u ", block_size_size, convert_blocks (ST_NBLOCKS (f->stat),
  1612.                              kilobyte_blocks));
  1613.  
  1614.   print_name_with_quoting (f->name);
  1615.  
  1616.   if (indicator_style != none)
  1617.     print_type_indicator (f->stat.st_mode);
  1618. }
  1619.  
  1620. void
  1621. print_type_indicator (mode)
  1622.      unsigned int mode;
  1623. {
  1624.   switch (mode & S_IFMT)
  1625.     {
  1626.     case S_IFDIR:
  1627.       putchar ('/');
  1628.       break;
  1629.  
  1630. #ifdef S_IFLNK
  1631.     case S_IFLNK:
  1632.       putchar ('@');
  1633.       break;
  1634. #endif
  1635.  
  1636. #ifdef S_IFIFO
  1637.     case S_IFIFO:
  1638.       putchar ('|');
  1639.       break;
  1640. #endif
  1641.  
  1642. #ifdef S_IFSOCK
  1643.     case S_IFSOCK:
  1644.       putchar ('=');
  1645.       break;
  1646. #endif
  1647.  
  1648.     case S_IFREG:
  1649.       if (indicator_style == all
  1650.       && (mode & (S_IEXEC | S_IEXEC >> 3 | S_IEXEC >> 6)))
  1651.     putchar ('*');
  1652.       break;
  1653.     }
  1654. }
  1655.  
  1656. int
  1657. length_of_file_name_and_frills (f)
  1658.      struct file *f;
  1659. {
  1660.   register char *p = f->name;
  1661.   register char c;
  1662.   register int len = 0;
  1663.  
  1664.   if (print_inode)
  1665.     len += 7;
  1666.  
  1667.   if (print_block_size)
  1668.     len += 1 + block_size_size;
  1669.  
  1670.   if (quote_as_string)
  1671.     len += 2;
  1672.  
  1673.   while (c = *p++)
  1674.     {
  1675.       if (quote_funny_chars)
  1676.     {
  1677.       switch (c)
  1678.         {
  1679.         case '\\':
  1680.         case '\n':
  1681.         case '\b':
  1682.         case '\r':
  1683.         case '\t':
  1684.         case '\f':
  1685.         case ' ':
  1686.           len += 2;
  1687.           break;
  1688.  
  1689.         case '"':
  1690.           if (quote_as_string)
  1691.         len += 2;
  1692.           else
  1693.         len += 1;
  1694.           break;
  1695.  
  1696.         default:
  1697.           if (c >= 040 && c < 0177)
  1698.         len += 1;
  1699.           else
  1700.         len += 4;
  1701.         }
  1702.     }
  1703.       else
  1704.     len += 1;
  1705.     }
  1706.  
  1707.   if (indicator_style != none)
  1708.     {
  1709.       unsigned filetype = f->stat.st_mode & S_IFMT;
  1710.  
  1711.       if (filetype == S_IFREG)
  1712.     {
  1713.       if (indicator_style == all
  1714.           && (f->stat.st_mode & (S_IEXEC | S_IEXEC >> 3 | S_IEXEC >> 6)))
  1715.         len += 1;
  1716.     }
  1717.       else if (filetype == S_IFDIR
  1718. #ifdef S_IFLNK
  1719.            || filetype == S_IFLNK
  1720. #endif
  1721. #ifdef S_IFIFO
  1722.            || filetype == S_IFIFO
  1723. #endif
  1724. #ifdef S_IFSOCK
  1725.            || filetype == S_IFSOCK
  1726. #endif
  1727.            )
  1728.     len += 1;
  1729.     }
  1730.  
  1731.   return len;
  1732. }
  1733.  
  1734. void
  1735. print_many_per_line ()
  1736. {
  1737.   int filesno;            /* Index into files. */
  1738.   int row;            /* Current row. */
  1739.   int max_name_length;        /* Length of longest file name + frills. */
  1740.   int name_length;        /* Length of each file name + frills. */
  1741.   int pos;            /* Current character column. */
  1742.   int cols;            /* Number of files across. */
  1743.   int rows;            /* Maximum number of files down. */
  1744.  
  1745.   /* Compute the maximum file name length.  */
  1746.   max_name_length = 0;
  1747.   for (filesno = 0; filesno < files_index; filesno++)
  1748.     {
  1749.       name_length = length_of_file_name_and_frills (files + filesno);
  1750.       if (name_length > max_name_length)
  1751.     max_name_length = name_length;
  1752.     }
  1753.  
  1754.   /* Allow at least two spaces between names.  */
  1755.   max_name_length += 2;
  1756.  
  1757.   /* Calculate the maximum number of columns that will fit. */
  1758.   cols = line_length / max_name_length;
  1759.   if (cols == 0)
  1760.     cols = 1;
  1761.   /* Calculate the number of rows that will be in each column except possibly
  1762.      for a short column on the right. */
  1763.   rows = files_index / cols + (files_index % cols != 0);
  1764.   /* Recalculate columns based on rows. */
  1765.   cols = files_index / rows + (files_index % rows != 0);
  1766.  
  1767.   for (row = 0; row < rows; row++)
  1768.     {
  1769.       filesno = row;
  1770.       pos = 0;
  1771.       /* Print the next row.  */
  1772.       while (1)
  1773.     {
  1774.       print_file_name_and_frills (files + filesno);
  1775.       name_length = length_of_file_name_and_frills (files + filesno);
  1776.  
  1777.       filesno += rows;
  1778.       if (filesno >= files_index)
  1779.         break;
  1780.  
  1781.       indent (pos + name_length, pos + max_name_length);
  1782.       pos += max_name_length;
  1783.     }
  1784.       putchar ('\n');
  1785.     }
  1786. }
  1787.  
  1788. void
  1789. print_horizontal ()
  1790. {
  1791.   int filesno;
  1792.   int max_name_length;
  1793.   int name_length;
  1794.   int cols;
  1795.   int pos;
  1796.  
  1797.   /* Compute the maximum file name length.  */
  1798.   max_name_length = 0;
  1799.   for (filesno = 0; filesno < files_index; filesno++)
  1800.     {
  1801.       name_length = length_of_file_name_and_frills (files + filesno);
  1802.       if (name_length > max_name_length)
  1803.     max_name_length = name_length;
  1804.     }
  1805.  
  1806.   /* Allow two spaces between names.  */
  1807.   max_name_length += 2;
  1808.  
  1809.   cols = line_length / max_name_length;
  1810.   if (cols == 0)
  1811.     cols = 1;
  1812.  
  1813.   pos = 0;
  1814.   name_length = 0;
  1815.  
  1816.   for (filesno = 0; filesno < files_index; filesno++)
  1817.     {
  1818.       if (filesno != 0)
  1819.     {
  1820.       if (filesno % cols == 0)
  1821.         {
  1822.           putchar ('\n');
  1823.           pos = 0;
  1824.         }
  1825.       else
  1826.         {
  1827.           indent (pos + name_length, pos + max_name_length);
  1828.           pos += max_name_length;
  1829.         }
  1830.     }
  1831.  
  1832.       print_file_name_and_frills (files + filesno);
  1833.  
  1834.       name_length = length_of_file_name_and_frills (files + filesno);
  1835.     }
  1836.   putchar ('\n');
  1837. }
  1838.  
  1839. void
  1840. print_with_commas ()
  1841. {
  1842.   int filesno;
  1843.   int pos, old_pos;
  1844.  
  1845.   pos = 0;
  1846.  
  1847.   for (filesno = 0; filesno < files_index; filesno++)
  1848.     {
  1849.       old_pos = pos;
  1850.  
  1851.       pos += length_of_file_name_and_frills (files + filesno);
  1852.       if (filesno + 1 < files_index)
  1853.     pos += 2;        /* For the comma and space */
  1854.  
  1855.       if (old_pos != 0 && pos >= line_length)
  1856.     {
  1857.       putchar ('\n');
  1858.       pos -= old_pos;
  1859.     }
  1860.  
  1861.       print_file_name_and_frills (files + filesno);
  1862.       if (filesno + 1 < files_index)
  1863.     {
  1864.       putchar (',');
  1865.       putchar (' ');
  1866.     }
  1867.     }
  1868.   putchar ('\n');
  1869. }
  1870.  
  1871. struct userid
  1872. {
  1873.   unsigned short uid;
  1874.   char *name;
  1875.   struct userid *next;
  1876. };
  1877.  
  1878. struct userid *user_alist;
  1879.  
  1880. /* Translate `uid' to a login name, with cache.  */
  1881.  
  1882. char *
  1883. getuser (uid)
  1884.      unsigned short uid;
  1885. {
  1886.   register struct userid *tail;
  1887.   struct passwd *pwent;
  1888.   char usernum_string[20];
  1889.  
  1890.   for (tail = user_alist; tail; tail = tail->next)
  1891.     if (tail->uid == uid)
  1892.       return tail->name;
  1893.  
  1894.   pwent = getpwuid (uid);
  1895.  
  1896.   tail = (struct userid *) xmalloc (sizeof (struct userid));
  1897.   tail->uid = uid;
  1898.   tail->next = user_alist;
  1899.   if (pwent == 0)
  1900.     {
  1901.       sprintf (usernum_string, "%u", (unsigned short) uid);
  1902.       tail->name = copystring (usernum_string);
  1903.     }
  1904.   else
  1905.     tail->name = copystring (pwent->pw_name);
  1906.   user_alist = tail;
  1907.   return tail->name;
  1908. }
  1909.  
  1910. /* We use the same struct as for userids.  */
  1911. struct userid *group_alist;
  1912.  
  1913. /* Translate `gid' to a group name, with cache.  */
  1914.  
  1915. char *
  1916. getgroup (gid)
  1917.      unsigned short gid;
  1918. {
  1919.   register struct userid *tail;
  1920.   struct group *grent;
  1921.   char groupnum_string[20];
  1922.  
  1923.   for (tail = group_alist; tail; tail = tail->next)
  1924.     if (tail->uid == gid)
  1925.       return tail->name;
  1926.  
  1927.   grent = getgrgid (gid);
  1928.   tail = (struct userid *) xmalloc (sizeof (struct userid));
  1929.   tail->uid = gid;
  1930.   tail->next = group_alist;
  1931.   if (grent == 0)
  1932.     {
  1933.       sprintf (groupnum_string, "%u", (unsigned int) gid);
  1934.       tail->name = copystring (groupnum_string);
  1935.     }
  1936.   else
  1937.     tail->name = copystring (grent->gr_name);
  1938.   group_alist = tail;
  1939.   return tail->name;
  1940. }
  1941.  
  1942. /* Assuming cursor is at position `from', indent up to position `to'.  */
  1943.  
  1944. void
  1945. indent (from, to)
  1946.      int from, to;
  1947. {
  1948.   while (from < to)
  1949.     {
  1950.       if (to / tabsize > from / tabsize)
  1951.     {
  1952.       putchar ('\t');
  1953.       from += tabsize - from % tabsize;
  1954.     }
  1955.       else
  1956.     {
  1957.       putchar (' ');
  1958.       from++;
  1959.     }
  1960.     }
  1961. }
  1962.  
  1963. /* Low level subroutines of general use,
  1964.    not specifically related to the task of listing a directory.  */
  1965.  
  1966. #ifndef MSDOS
  1967.  
  1968. char *
  1969. xrealloc (obj, size)
  1970.      char *obj;
  1971.      int size;
  1972. {
  1973.   char *val = realloc (obj, size);
  1974.  
  1975.   if (!val)
  1976.     error (1, 0, "virtual memory exhausted");
  1977.  
  1978.   return val;
  1979. }
  1980.  
  1981. char *
  1982. xmalloc (size)
  1983.      int size;
  1984. {
  1985.   char *val = malloc (size);
  1986.  
  1987.   if (!val)
  1988.     error (1, 0, "virtual memory exhausted");
  1989.  
  1990.   return val;
  1991. }
  1992.  
  1993. #endif /* MSDOS */
  1994.  
  1995. /* Return a newly allocated copy of `string'. */
  1996.  
  1997. char *
  1998. copystring (string)
  1999.      char *string;
  2000. {
  2001.   return strcpy ((char *) xmalloc (strlen (string) + 1), string);
  2002. }
  2003.  
  2004. /* Put `dirname/name' into `dest', handling `.' and `/' properly. */
  2005.  
  2006. void
  2007. attach (dest, dirname, name)
  2008.      char *dest, *dirname, *name;
  2009. {
  2010.   char *dirnamep = dirname;
  2011.  
  2012.   /* Copy dirname if it is not ".". */
  2013.   if (dirname[0] != '.' || dirname[1] != 0)
  2014.     {
  2015.       while (*dirnamep)
  2016.     *dest++ = *dirnamep++;
  2017.       /* Add '/' if `dirname' doesn't already end with it. */
  2018.       if (dirnamep > dirname && dirnamep[-1] != '/')
  2019.     *dest++ = '/';
  2020.     }
  2021.   while (*name)
  2022.     *dest++ = *name++;
  2023.   *dest = 0;
  2024. }
  2025.  
  2026. void
  2027. usage ()
  2028. {
  2029.   fprintf (stderr, "\
  2030. Usage: %s [-abcdgiklmnpqrstuxABCFLNQRSUX1] [-w cols] [-T cols] [-I pattern]\n\
  2031.        [+all] [+escape] [+directory] [+inode] [+kilobytes]\n\
  2032.        [+numeric-uid-gid] [+hide-control-chars] [+reverse] [+size]\n\
  2033.        [+width cols] [+tabsize cols] [+almost-all] [+ignore-backups]\n",
  2034.        program_name);
  2035. #ifdef MSDOS
  2036.   fprintf (stderr, "\
  2037.        [+classify] [+file-type] [+ignore pattern] [+dereference] [+literal]\n\
  2038.        [+quote-name] [+recursive] [+sort {none,time,size,extension}]\n\
  2039.        [+format {long,verbose,commas,across,vertical,single-column}]\n\
  2040.        [+time {atime,access,use,ctime,status}] [+copying] [+version]\n\
  2041.        [path...]\n");
  2042. #else /* not MSDOS */
  2043.   fprintf (stderr, "\
  2044.        [+classify] [+file-type] [+ignore pattern] [+dereference] [+literal]\n\
  2045.        [+quote-name] [+recursive] [+sort {none,time,size,extension}]\n\
  2046.        [+format {long,verbose,commas,across,vertical,single-column}]\n\
  2047.        [+time {atime,access,use,ctime,status}] [path...]\n");
  2048. #endif /* not MSDOS */
  2049.   exit (1);
  2050. }
  2051.